package com.llb666.e.shop.api.controller;

import com.llb666.e.shop.api.vo.UsersVo;
import com.llb666.e.shop.domain.entity.Orders;
import com.llb666.e.shop.domain.entity.Users;
import com.llb666.e.shop.domain.service.MyOrdersService;
import com.llb666.e.shop.infracore.config.RedisOperator;
import com.llb666.e.shop.infracore.constants.AppConstant;
import com.llb666.e.shop.infracore.exception.AppException;
import com.llb666.e.shop.infracore.web.CommonError;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;

/**
 * @author 斌~
 * @date 2022/9/12 下午6:01
 */
public class BaseController {

    @Autowired
    private RedisOperator redisOperator;

    @Autowired
    public MyOrdersService myOrdersService;


    /**
     * 用于验证用户和订单是否有关联关系，避免非法用户调用.
     */
    public void checkUserOrder(String userId, String orderId) {
        Orders order = myOrdersService.queryMyOrder(userId, orderId);
        if (order == null) {
            throw new AppException(CommonError.NotAuthorized,"订单不存在");
        }
    }

    public UsersVo conventUsersVo(Users user){
        String uniqueToken = UUID.randomUUID().toString().trim();
        redisOperator.set(AppConstant.REDIS_USER_TOKEN+":"+user.getId(),uniqueToken);
        UsersVo usersVo = UsersVo.Converter.INSTANCE.do2Vo(user);
        usersVo.setUserUniqueToken(uniqueToken);
        return  usersVo;
    }
}
